import {
  AES_Encrypt,
  AES_Decrypt,
  MD5_Encrypt
} from "./crypto";
const baseServer = "https://cnapi.ttlock.com";
const CLIENT_ID = "7946f0d923934a61baefb3303de4d132";
const CLIENT_SECRET = "56d9721abbc3d22a58452c24131a5554";
const plugin = requirePlugin("myPlugin");
let keyList = [];
let TTLOps = {};
async function loginTTL() {
  const option = {
    "client_id": CLIENT_ID,
    "client_secret": CLIENT_SECRET,
    "grant_type": "password",
    "redirect_uri": "http://www.sciener.cn",
    "username": "13693388139",
    "password": MD5_Encrypt("W19870604"),
  };
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseServer}/oauth2/token`,
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: option,
      method: "POST",
      success: (res) => {
        const ret = res.data;
        TTLOps={
          user_id : AES_Encrypt(option.username),
          user_psd : AES_Encrypt(option.password),
          access_token : AES_Encrypt(ret.access_token),
          uid : AES_Encrypt(ret.uid)
        }
        return resolve(TTLOps)
      },
      fail: (err) => {
        return reject(err)
      }
    })
  })
}

async function getKeyList() {
  return new Promise((resolve,reject)=>{
    wx.request({
      url: `${baseServer}/v3/key/list`,
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        "clientId": CLIENT_ID,
        "accessToken": AES_Decrypt(TTLOps.access_token),
        "pageNo": 1,
        "pageSize": 20,
        "date": Date.now()
      },
      method: "POST",
      success: (response) => {
        const res = response.data;
        console.log(res);
        keyList=res.list;
        return resolve(keyList)
      },
      fail: (err) => {
        return resolve([])
      }
    })
  })
}

export async function toOpenDoor(lockName="",deviceId="") {
  await InitTTL()
  const lockData = keyList.find(item=>item.lockName === lockName)?.lockData;
  console.log(lockName)
  console.log(keyList)
  if (!lockData){
    wx.showToast({
      title: '开锁失败！',
      icon:"error"
    })
    return;
  }
  wx.showLoading({
    title: "正在开锁"
  });
  // 调用开锁接口 
  plugin.controlLock(plugin.ControlAction.OPEN, lockData, res => {
    console.log("控制智能锁时设备连接已断开", res);
  }, null, deviceId).then(res => {
    if (res.deviceId) deviceId = res.deviceId;
    if (res.errorCode === 0) {
      wx.showToast({
        icon: "success",
        title: "开锁成功"
      });
    } else if(res.errorCode === 10012){
      wx.showToast({
        icon: "error",
        title: "请先打开蓝牙",
        duration:2500
      });
    } else if(res.errorCode === 10002){
      wx.showToast({
        icon: "error",
        title: res.errorMsg,
        duration:2500
      });
    } else {
      wx.showToast({
        icon: "error",
        title: "开锁失败"
      });
    }
  })
}

async function InitTTL() {
  if(TTLOps.access_token === undefined){
    await loginTTL();
  }
  if(keyList.length === 0 ){
    await getKeyList();
  }
  return 1;
}